<?php

class MessagesController extends Controller
{
       
        
	public function actionIndex()
	{
                
				$pid = Yii::app()->request->getParam("pid");
                // get all message category assocative with project
                $modelMessageCategories = MessageCategory::model()->findAllByAttributes(array('message_category_project_id'=>$pid), array('order'=>'message_category_name ASC'));
                $messageCategories = array();
                foreach ($modelMessageCategories as $modelMessageCategory){
                    $listMessages = $modelMessageCategory->messages;
                    $messageCategory['listMessages'] = $listMessages;
                    $messageCategory['model']        = $modelMessageCategory;
                    $messageCategories[] = $messageCategory;
                }
                $this->render('index',array(
                    'messageCategories'=>$messageCategories,
                ));
	}

	// -----------------------------------------------------------
	// Uncomment the following methods and override them if needed
	/*
	public function filters()
	{
		// return the filter configuration for this controller, e.g.:
		return array(
			'inlineFilterName',
			array(
				'class'=>'path.to.FilterClass',
				'propertyName'=>'propertyValue',
			),
		);
	}

	public function actions()
	{
		// return external action classes, e.g.:
		return array(
			'action1'=>'path.to.ActionClass',
			'action2'=>array(
				'class'=>'path.to.AnotherActionClass',
				'propertyName'=>'propertyValue',
			),
		);
	}
	*/
	public function actionAddMessage()
	{
		$message = new Message();
		$messageCate = new MessageCategory();
		
		//get param
		$uid = Yii::app()->user->id;
		$pid = Yii::app()->request->getParam('pid');
		$messageName = Yii::app()->request->getPost('messageName');
		$selectCategory = Yii::app()->request->getPost('mcid');
		$content = Yii::app()->request->getPost('content');
		if ($pid == null)
			throw new CHttpException(404,'Param not enough');
		
		if (isset($_POST['Message'])) {
			//get data for message
			$message->attributes = $_POST['Message'];
			$message->message_sent_by_user_id = Yii::app()->user->id;
			$message->message_sent_date = new CDbExpression('NOW()');
			
			//get data for message category
			if ($message->message_category_id == '-'){
				if (!isset($_POST['MessageCategory'])){
					Yii::app()->user->setFlash('error','Error create new message category');
					$this->render('addMessage',array(
						'message'=>$message,	
						'messageCate'=>$messageCate,
					));
					return;
				}
				
				$messageCate->attributes = $_POST['MessageCategory'];
				$messageCate->message_category_project_id = $pid;
				if (!$messageCate->save()){
					Yii::app()->user->setFlash('error','Error create new message category');
					$this->render('addMessage',array(
						'message'=>$message,
						'messageCate'=>$messageCate,
					));
					return;
				}
				$message->message_category_id = $messageCate->message_category_id;
			}
			
			if ($message->save()) {
				// save message user
				if (isset($_POST['message_user']))
				foreach ($_POST['message_user'] as $userid) {
					$message_user = new MessageUser();
					$message_user->message_user_message_id = $message->message_id;
					$message_user->message_user_to_user_id = $userid;
					$message_user->save();
				}
				
				// send notifycation mail
				//$this->sendMail($message, $_POST['message_user']);
				Yii::app()->user->setFlash('success','New message created succeessful');
				$this->redirect(array('/messages/index','pid'=>$pid));
			}
		}	
			
		$this->render('addMessage',array(
			'message'=>$message,
			'messageCate'=>$messageCate,
		));
	}
	public function actionView()
	{
		//get param
		$pid = Yii::app()->request->getParam('pid');
		$mid = Yii::app()->request->getParam('mid');
		if (($pid == null) or ($mid ==null)) {
			throw new CHttpException('404','param not enought');
		}
		
		// get model
		$message = Message::model()->findByPk($mid);
		$this->render('view',array(
			'message'=>$message
		));
	}
	
	/**
	 * send new message to list user
	 */
	public function sendMail($message, $usersId) {
		$SM = Yii::app()->swiftMailer;
		$mailHost = 'localhost';
    		$mailPort = 25; // Optional
    	$content = $this->renderPartial('_mail', array(
        	'message' => $message,
    	), true);
    	$Transport = $SM->smtpTransport($mailHost, $mailPort);
    	$Mailer = $SM->mailer($Transport);

    	// New message
    	$pid = Yii::app()->request->getParam('pid');
    	$project = Project::model()->findByPk($pid);
    	$title = "[$project->project_name] {$message->message_subject}";
    	$Message = $SM
        ->newMessage('My subject')
        ->setFrom(array('xman@runsystem.net' => 'Xmanager'))
        ->addPart($content, 'text/html');
 
    	//Set receiver array
		$receiver = array();
    	foreach ($usersId as $userId) {
    		$user = User::model()->findByPk($userId);
			$receiver[$user->user_email] = $user->user_name;
    	}
		$Message->setTo ($receiver);
		$result = $Mailer->send($Message);
	}
	
	/**
	 * Del a message
	 */
	public function actionDel() {
		// get param
		$mid = Yii::app()->request->getParam('mid');
		$Message = new Message();
		$Message->deleteByPk($mid);
	}
	
	/** Edit a message
	 * 
	 */
public function actionEdit()
	{
		
		//get param
		$uid = Yii::app()->user->id;
		$pid = Yii::app()->request->getParam('pid');
		$mid = Yii::app()->request->getParam('mid');
		
		// get data for edit
		$message = Message::model()->findByPk($mid);
		$messageCate = $message->messageCategory;
		
		//$messageName = Yii::app()->request->getPost('messageName');
		//$selectCategory = Yii::app()->request->getPost('mcid');
		//$content = Yii::app()->request->getPost('content');
		if ($pid == null)
			throw new CHttpException(404,'Param not enough');
		
		if (isset($_POST['Message'])) {
			//get data for message
			$message->attributes = $_POST['Message'];
			$message->message_sent_by_user_id = Yii::app()->user->id;
			$message->message_sent_date = new CDbExpression('NOW()');
			
			//get data for message category
			if ($message->message_category_id == '-'){
				if (!isset($_POST['MessageCategory'])){
					Yii::app()->user->setFlash('error','Error create new message category');
					$this->render('edit',array(
						'message'=>$message,	
						'messageCate'=>$messageCate,
					));
					return;
				}
				
				$messageCate->attributes = $_POST['MessageCategory'];
				$messageCate->message_category_project_id = $pid;
				if (!$messageCate->save()){
					Yii::app()->user->setFlash('error','Error create new message category');
					$this->render('edit',array(
						'message'=>$message,
						'messageCate'=>$messageCate,
					));
					return;
				}
				$message->message_category_id = $messageCate->message_category_id;
			}
			
			if ($message->save()) {
				Yii::app()->user->setFlash('success','Message saved successful');
				$this->redirect(array('/messages/index','pid'=>$pid));
			}
		}	
			
		$this->render('edit',array(
			'message'=>$message,
			'messageCate'=>$messageCate,
		));
	}
}